<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Cates extends Model
{
    public $dateFormat = 'U';
    public $table = 'cates';

    /**
     * @param int $type     导航类型
     * @param bool $status  是否只取未软删除
     * @param null $structure 结构
     * @return array
     */
    public static function lists($status=false,$structure=null,$mark='child')
    {
        $data = self::orderBy('sort','asc')
            ->get();

        if($structure=='tree'){
            return self::tree($data->toArray(),0,$mark);
        }
        if($structure=='plumb'){
            return self::plumb($data->toArray(),0,$mark);
        }

        return $data;
    }

    /** 树形结构 */
    public static function tree($model,$pid=0,$child='child')
    {
        $data = array();
        foreach($model as $item){
            if($pid == $item['pid']){
                $item[$child] = self::tree($model,$item['id'],$child);
                $data[] = $item;
            }
        }
        return $data;
    }

    /** 排序结构 */
    public static function plumb($model,$pid=0,$prefix='--')
    {
        $data = array();
        foreach($model as $item){
            if($item['pid']==$pid){
                $item['name'] = $prefix.$item['name'];
                $data[] = $item;
                $child = self::plumb($model,$item['id'],$prefix.$prefix);
                $data = array_merge($data,$child);
            }
        }

        return $data;
    }
}
